package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-manager/cache"
	"pet-manager/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if name == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	pet := models.Pet{
		Name:    name,
		Content: content,
		Img:     img,
	}
	models.DB.Create(&pet)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "1"))
	offset := (page - 1) * size
	var data []models.Pet
	redis_key := "pet_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Order("created_at desc").Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var count int64
	models.DB.Model(&models.Pet{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"count": count,
	})
	return
}
